package org.example.ideavr.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import jakarta.servlet.http.HttpServletResponse;
import org.example.ideavr.annotation.AutoFill;
import org.example.ideavr.common.context.BaseContext;
import org.example.ideavr.common.result.PageResult;
import org.example.ideavr.mapper.GameMapper;
import org.example.ideavr.pojo.dto.GamePageQueryDTO;
import org.example.ideavr.pojo.entity.Game;
import org.example.ideavr.service.GameService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class GameServiceImpl implements GameService {

    @Autowired
    GameMapper gameMapper;

    /**
     * 上传游戏
     */
    @Override
    @AutoFill
    public void gameUpload(Game game) {

        game.setUserId(BaseContext.getThreadLocal());
        game.setCreateTime(LocalDateTime.now());
        game.setUpdateTime(LocalDateTime.now());
        gameMapper.insert(game);
    }

    /**
     * 下载游戏
     */
    @Override
    public String gameDownload(HttpServletResponse response, Long gameId) throws IOException {
        Game game = gameMapper.selectById(gameId);
        if(game == null) {
            throw new RuntimeException("游戏不存在");
        }

        //设置文件路径
        String directory = "D:\\update\\game\\";
        Path file = Paths.get(directory, game.getFileUrl());

        if(!Files.exists(file)) {
            throw new RuntimeException("文件不存在");
        }
        //设置响应头
        response.setContentType("application/octet-stream");
        response.addHeader("Content-Disposition", "attachment:filename=" + game.getFileUrl());
        response.addHeader("Content-Length", String.valueOf(Files.size(file)));

        //读取文件到流
        try(InputStream inputStream = new BufferedInputStream(new FileInputStream(String.valueOf(file)));
            OutputStream outputStream = response.getOutputStream()){
            byte[] buffer = new byte[1024];
            int bytesRead;
            while((bytesRead = inputStream.read(buffer)) != -1){
                outputStream.write(buffer, 0, bytesRead);
            }
            //清空输出流

        }catch (IOException e){
            throw new RuntimeException("下载失败",e);
        }



        return "下载完成";

    }

    @Override
    public void gameUpdate(Long gameId, Game game) {
        if( gameMapper.selectById(gameId).getId().equals(BaseContext.getThreadLocal())){
            throw new RuntimeException("没有权限");
        }
        game.setUpdateTime(LocalDateTime.now());
        game.setId(gameId);
        gameMapper.updateById(game);
    }

    @Override
    public Game getGameById(Long gameId) {
        return gameMapper.selectById(gameId);
    }


    /**
     * 分页查询游戏列表
     */
    @Override
    public PageResult gamePage(GamePageQueryDTO gamePageQueryDTO) {

        PageHelper.startPage(gamePageQueryDTO.getPageNum(), gamePageQueryDTO.getPageSize());
        Page<Game> page = gameMapper.pageQuery(gamePageQueryDTO);
        long Total = page.getTotal();
        List<Game> records = page.getResult();

        return new PageResult(Total, records);
    }
}
